package com.zhuhanpeng.cloud.user.service.impl;

import com.zhuhanpeng.cloud.api.entity.registerEntity;
import com.zhuhanpeng.cloud.exception.EmailExitException;
import com.zhuhanpeng.cloud.exception.MobileExitException;
import com.zhuhanpeng.cloud.exception.UserNameExitException;
import com.zhuhanpeng.cloud.file.control.FileController;
import com.zhuhanpeng.cloud.mybatis.entity.PtUserEntity;
import com.zhuhanpeng.cloud.mybatis.flexigrid.PadingRstType;
import com.zhuhanpeng.cloud.mybatis.flexigrid.PagingEntity;
import com.zhuhanpeng.cloud.mybatis.ztree.ZtreeEntity;
import com.zhuhanpeng.cloud.spring.entity.GdmtUserEntity;
import com.zhuhanpeng.cloud.spring.util.CloudUtil;
import com.zhuhanpeng.cloud.user.entity.SearchUserEntity;
import com.zhuhanpeng.cloud.user.entity.UserEntity;
import com.zhuhanpeng.cloud.user.exception.PasswordError;
import com.zhuhanpeng.cloud.user.repository.UserDao;
import com.zhuhanpeng.cloud.user.service.UserService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    private Logger logger = LogManager.getLogger(FileController.class);
    @Resource
    private UserDao userDao;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private MessageSource messageSource;

    @Override
    public void modifyPassword(String oldPassword, String newPassword) throws PasswordError {
        GdmtUserEntity gdmtUserEntity = (GdmtUserEntity) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        String oldPasswdEnc = passwordEncoder.encode(oldPassword);
        PtUserEntity entity = userDao.queryUserInfoByIdAndPasswd(gdmtUserEntity.getUserUuid(), oldPasswdEnc);
        if (entity == null) {
            throw new PasswordError("old password error");
        }
        String passwordEnc = passwordEncoder.encode(newPassword);
        userDao.modifyPasswordById(passwordEnc, gdmtUserEntity.getUserUuid());

    }

    @Override
    public PadingRstType<PtUserEntity> queryUserInfoListByPage(SearchUserEntity entity, PagingEntity paging) {
        paging.dealOrder(PtUserEntity.class);
        PadingRstType<PtUserEntity> ptUserEntityPadingRstType = new PadingRstType<>();
        ptUserEntityPadingRstType.setPage(paging.getPage());
        Integer total = userDao.queryUserListTotal(entity);
        ptUserEntityPadingRstType.setTotal(total);
        List<PtUserEntity> list = userDao.queryUserInfoListByPage(entity, paging);
        ptUserEntityPadingRstType.setRawRecords(list);
        ptUserEntityPadingRstType.putItem();
        return ptUserEntityPadingRstType;
    }

    @Override
    public void addUser(UserEntity entity) throws UserNameExitException, EmailExitException, MobileExitException {
        Integer count = userDao.queryUserCountByUserName(entity.getUserName());
        logger.info("count" + count);
        if (count != 0 && count != null) {
            throw new UserNameExitException("userName" + entity.getUserName());
        }
//        count = userDao.queryUserCountByEmail(entity.getEmail());
//        if (count > 0) {
//            throw new EmailExitException("email" + entity.getEmail());
//        }
//        String mobile = entity.getMobile();
//        if (mobile != null && (!"".equals(mobile))) {
//            count = userDao.queryUserCountByMobile(entity.getMobile());
//            logger.info(count);
//            if (count > 0) {
//                throw new MobileExitException("mobile" + entity.getMobile());
//            }
//        }
        entity.setUserUuid(CloudUtil.generateUuid());
        String password = passwordEncoder.encode(entity.getPassword());
        entity.setPassword(password);
        userDao.addUser(entity);
    }

    @Override
    public UserEntity queryUserInfoById(String userUuid) {
        return userDao.queryUserInfoById(userUuid);
    }

    @Override
    public void modifyUser(UserEntity entity) throws UserNameExitException, EmailExitException, MobileExitException {
        Integer count = userDao.queryUserCountByUserNameNotId(entity.getUserName(), entity.getUserUuid());
        if (count > 0) {
            throw new UserNameExitException("userName" + entity.getUserName());
        }
        count = userDao.queryUserCountByEmailNotId(entity.getEmail(), entity.getUserUuid());
        if (count > 0) {
            throw new EmailExitException("email" + entity.getEmail());
        }
        String mobile = entity.getMobile();
        if (mobile != null && (!"".equals(mobile))) {
            count = userDao.queryUserCountByMobileNotId(entity.getMobile(), entity.getUserUuid());
            if (count > 0) {
                throw new MobileExitException("mobile" + entity.getMobile());
            }
        }

        userDao.modifyUserById(entity);
    }

    @Override
    public void deleteUserInfoByIds(String userUuids) {
        String[] userUuidArray = userUuids.split(",");
        userDao.deleteUserInfoByIds(userUuidArray);
    }

    @Override
    public List<ZtreeEntity> queryRoleZtreeByUserId(String userUuid) {
        List<ZtreeEntity> ztreeEntityList = queryRoleZtreeAll();
        //获取选中状态
        List<String> roleIdList = userDao.queryRoleByUserId(userUuid);
        for (ZtreeEntity item : ztreeEntityList) {
            for (String roleUuid : roleIdList) {
                if (roleUuid.equals(item.getId())) {
                    item.setChecked(true);
                    break;
                }
            }
        }

        return ztreeEntityList;
    }

    @Override
    public void saveRoleRefUser(String userUuidArray, String rolesArray) {
        String[] userUuids = userUuidArray.split(",");
        String[] roles = rolesArray.split(",");
        for (String userUuid : userUuids) {
            userDao.deleteRoleByUser(userUuid);
            for (String roleUuid : roles) {
                userDao.insertRoleRefUser(userUuid, roleUuid);
            }

        }

    }

    @Override
    public List<ZtreeEntity> queryRoleZtreeAll() {
        List<ZtreeEntity> ztreeEntityList = userDao.queryRoleZtree();
        ZtreeEntity ztreeEntity = new ZtreeEntity();
        //增加根节点
        String msg = messageSource.getMessage("user.role.manager", null, LocaleContextHolder.getLocale());
        ztreeEntity.setName(msg);
        ztreeEntity.setId("-1");
        ztreeEntity.setpId("-2");
        ztreeEntityList.add(ztreeEntity);
        return ztreeEntityList;
    }

    @Override
    public void resetPassword(String userUuidArray, String password) {
        String encPassword = passwordEncoder.encode(password);
        String[] userUuids = userUuidArray.split(",");
        userDao.resetPasswordByIds(userUuids, encPassword);
    }
}